//工具函数库，仔仔编写。
import config from "@/config";
import store from '@/store/index.js';

function APIURL() {
	if (config.env === 'online') {
		return config.API_URL_ONLINE;
	} else if (config.env === 'test') {
		return config.API_URL_TEST;
	} else {
		return config.API_URL_DEV;
	}
}

let _tool = {
	//获取字符串的真实长度（字节长度）
	strLeng(str) {
		if(str) {
			let len = str.length, truelen = 0;
			for(let x = 0; x < len; x++) {
				if(str.charCodeAt(x) > 128){
					truelen += 2;
				}else{
					truelen += 1;
				}
			}
			return truelen;
		} else {
			return 0;
		}
	},
	//计算页数
	getPageNum(total,row) {
		let num = Number(total) / Number(row);
		//是否为整数
		if(num%1 !== 0) {
			let b = num.toString();	//转字符串
			let a = parseInt(b.substring(0,b.indexOf('.')));	//取小数点前
			let s = b.replace(/\d+\.(\d*)/, '$1');	//取小数点后
			if(s > 0) {
				num = a + 1;
			}
		}
		return num;
	},
	//设置手机通知栏字体颜色
	setBarColor(black = false) {
		if(black) {
			uni.setNavigationBarColor({
			    frontColor: '#000000',
			    backgroundColor: '#FAFAFA'
			});
		} else {
			uni.setNavigationBarColor({
			    frontColor: '#ffffff',
			    backgroundColor: '#FAFAFA'
			});
		}
	},
	zaiui_log(v) {
		
	},
	chooseImage(callback) {
	  uni.chooseImage({
	    count: 1,
	    sourceType: ['album'],
	    success: res => {
	      uni.getImageInfo({
	        src: res.tempFilePaths[0],
	        success: image => {
	          console.log(image)
	          uni.showLoading({ title: '图片上传中', mask: true })
	          uni.uploadFile({
	            url: APIURL()+"/file/upload",
	            file: image,
	            filePath: image.path,
	            header: {
	              sToken:  store.getters.token,
	            },
	            name: 'file',
	            success: res => {
	              if (callback) {
	                callback(JSON.parse(res.data).data)
	              }
	            },
	            fail: err => {
	              uni.showToast({
	                title: '上传图片失败',
	                icon: 'none',
	                duration: 2000,
	              })
	            },
	            complete: res => {
	              uni.hideLoading()
	            },
	          })
	        },
	        fail: err => {
	          uni.showToast({
	            title: '获取图片信息失败',
	            icon: 'none',
	            duration: 2000,
	          })
	        },
	      })
	    },
	  })
	}
};

export default _tool;